﻿using BasicInformation.Domain;
using BasicInformation.Infrastructure.Iml;
using BasicInformation.Infrastructure.Interface;
using BasicInformation.ReadAPI.Application.Command.OwnerCommand;
using MediatR;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.IdentityModel.Tokens;
using PublicCommon;

namespace BasicInformation.ReadAPI.Application.CommandHandler.OwnerCommandHandler
{
    public class OwnerListCommandHandler : IRequestHandler<OwnerListCommand, PageResult<Owner>>
    {
        private readonly IOwnerRepository ownerRepository;

        public OwnerListCommandHandler(IOwnerRepository ownerRepository)
        {
            this.ownerRepository = ownerRepository;
        }

        public async Task<PageResult<Owner>> Handle(OwnerListCommand request, CancellationToken cancellationToken)
        {
            var list = ownerRepository.GetList().Result.Where(x => !x.IsDel).AsQueryable();
            if (!string.IsNullOrEmpty(request.OwnersName))
            {
                list = list.Where(x => x.OwnersName.Contains(request.OwnersName));
            }
            if (!string.IsNullOrEmpty(request.PhoneNumber))
            {
                list = list.Where(x => x.PhoneNumber.Contains(request.PhoneNumber));
            }
            if (!string.IsNullOrEmpty(Convert.ToString(request.ValidDate)))
            {
                list = list.Where(x => x.ValidDate==request.ValidDate);
            }
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            var pagelist = list.OrderByDescending(x => x.Id).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return new PageResult<Owner>
            {
                List = pagelist,
                PageCount = pageCount,
                TotalCount = totalCount
            };
        }
    }
}
